package samsung.sds.systemMonitor.SQLMonitor.intercept;

import java.math.BigDecimal;
import java.util.HashMap;

import org.apache.ibatis.plugin.Invocation;

import samsung.sds.systemMonitor.SQLMonitor.model.SQLMonitorEntity;

/**
 * @author wei5.gao
 * @createDate 2016-02-22
 * 
 * custom模式SQL日志拦截器(sql类型C/R/U/D拦截，可支持多类型如CR，CRD等)
 */
public class CustomSQLMonitor extends SQLMonitorHandlerImpl{
	
	public Object saveSQLMonitorEntity(HashMap<String,Object> map) throws Throwable{
		SQLMonitorEntity entity = new SQLMonitorEntity();
		Invocation invocation=(Invocation) map.get("invocation");
		String interceptorType= map.get("interceptorType").toString();
		entity = fillEntity(entity,invocation);
		Object returnValue = null;
		// 定义插入数据库的SQLMonitorEntity
		try {
			// 通过获取request拿到当下URL
			long start = System.currentTimeMillis();
			returnValue = invocation.proceed();
		    long end = System.currentTimeMillis();
			entity.setExecResult("1");
			entity.setExecTime(new BigDecimal(end-start));
			entity.setEffectRows(getEffctRows(entity.getSqlType(), returnValue));
		} catch (Exception e) {
			entity.setExecResult("0");
			entity.setExecTime(BigDecimal.ZERO);
			entity.setEffectRows(BigDecimal.ZERO);
			String errorMessage = getStackInfo(e);
			entity.setSqlContent(entity.getSqlContent()+"--------------------------------------"
					+ "------------------------------------------------------------------------"
					+ "---------------------------------------ExceptionMessage:" +errorMessage);
			throw e;
		} finally {
			if(insertCondition(entity.getUrl(), entity.getSqlId())&&((interceptorType.split("-")[0]).contains(entity.getSqlType()))){
				super.getSQLMonitorServiceImpl().sqlMonitorSpecialSave(entity);
			}
		}
		return returnValue;
	}
}
